package com.cy.sca.api.aspect;

//import com.cy.sca.member.feign.RemoteNoticeService;
import com.cy.sca.api.feign.RemoteNoticeService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LogAspect
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/6/9 11:07
 * @Version V1.0
 **/
@Aspect//描述此类为切面类,其中可加AOP注解
@Component//交给spring容器
public class LogAspect {
    @Autowired
   private RemoteNoticeService remoteNoticeService;
    private static final Logger log=
             LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.cy.sca.api.annotation.RequiredLog)")
    public  void doLog(){}//目标方法的位置
        @Around("doLog()")//@Around目标方法
        public Object doAround(ProceedingJoinPoint jp)throws Throwable{
        //1.解析目标方法
            Map<String, Object> logInfo = new HashMap<>();
            String targetClassName = jp.getTarget().getClass().getName();
            logInfo.put("targetClassName", targetClassName);
            //System.out.println("targetClassName="+targetClassName);
            Signature signature = jp.getSignature();
            String methodName = signature.getName();
            logInfo.put("targetMethod", methodName);
            //System.out.println("methodName="+methodName);
            Object[] args = jp.getArgs();
            String jsonArgs = new ObjectMapper().writeValueAsString(args);
            logInfo.put("requestParams", jsonArgs);
            //System.out.println("jsonArgs="+jsonArgs);

        //2.时间
            long t1 = System.currentTimeMillis();
            System.out.println("start:"+t1);

            try {
                Object result = jp.proceed();//执行切面链
                long t2 = System.currentTimeMillis();
                long time=t2-t1;
                System.out.println("after:"+t2);
                return result;
            }catch (Throwable e){
                long t3 = System.currentTimeMillis();
                long time=t3-t1;
                System.out.println("error:"+t3);
                throw e;
            }finally {
                log.info("operation log {} ",logInfo.toString());
              remoteNoticeService.doLoginfo(logInfo);
            }



    }
}
